{% extends 'base/base.html' %}
{% load static %}
{% load humanize %}
{% load permission_tags %}

{% block title %}
Organizations
{% endblock title %}

{% block custom_js_css_link %}
{% endblock custom_js_css_link %}

{% block breadcrumb_title %}
<li class="breadcrumb-item active"><a href="{% url 'list_organization' current_project.slug %}">Organization</a></li>
{% endblock breadcrumb_title %}

{% block page_title %}
Organizations
{% endblock page_title %}

{% block main_content %}
<div class="row">
  <div class="col-12">
    <div class="card">
      <div class="p-2">
        <div class="row">
          <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
          </div>
          <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
            {% if user|can:'modify_targets' %}
            <a class="btn btn-soft-danger float-end disabled ms-1" href="#" onclick="deleteMultipleOrganizations()" id="delete_multiple_button">Delete Multiple Organizations</a>
            <a class="btn btn-soft-primary float-end ms-1" href="{% url 'add_organization' current_project.slug %}" data-toggle="tooltip" data-placement="top" title="Add Organization">Add New Organization</a>
            {% endif %}
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-12">
    <div class="card">
      <table id="list_organization_table" class="table dt-responsive w-100">
        <thead>
          <tr>
            <th class="checkbox-column text-center">
              <div class="form-check mb-2 form-check-primary">
                <input type="checkbox" class="form-check-input" id="select_all_checkbox" onchange="selectAllOrganizations(this)">
              </div>
            </th>
            <th class="">Organization</th>
            <th class="text-center">Description</th>
            <th class="text-center">Total Targets</th>
            <th class="text-center">Added</th>
            <th class="text-center">Action</th>
          </tr>
        </thead>
        <tbody>
          {% for organization in organizations.all %}
          <tr>
            <td class="checkbox-column text-center">
              <div class="form-check mb-2 form-check-primary">
                <input type="checkbox" class="form-check-input organization-checkbox" value="{{ organization.id }}" onchange="toggleMultipleOrganizationButton()">
              </div>
            </td>
            <td class="">{{ organization.name|capfirst }}</td>
            <td class="text-center">{% if organization.description %}{{organization.description}}{% endif %}</td>
            <td class="text-center"><span class="badge bg-primary badge-link" onclick="get_target_modal({{organization.id}})">{{organization.get_domains.count}}</span></td>
            <td class="text-center"><span data-toggle="tooltip" data-placement="top" title="{{organization.insert_date}}">{{organization.insert_date|naturaltime}}</span></td>
            <td class="text-center">
              <div class="btn-group float-end">
                {% if user|can:'initiate_scans_subscans' %}
                  <a href="/scan/{{current_project.slug}}/start/organization/{{organization.id}}" class="btn btn-soft-primary"><i class="fe-zap"></i>&nbsp;&nbsp;Initiate Scan</a>
                {% endif %}
                <div class="btn-group dropstart" role="group">
                  <button type="button" class="btn btn-soft-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="mdi mdi-chevron-right"></i>
                  </button>
                  <div class="dropdown-menu" style="">
                    {% if user|can:'initiate_scans_subscans' %}
                      <a class="dropdown-item" href="{% url 'schedule_organization_scan' current_project.slug organization.id %}"><i class="fe-clock"></i>&nbsp;&nbsp;Schedule Scan</a>
                    {% endif %}
                    {% if user|can:'modify_targets' %}
                      <a class="dropdown-item" href="/target/{{current_project.slug}}/update/organization/{{organization.id}}"><i class="fe-edit-2"></i>&nbsp;&nbsp;Edit Organization</a>
                    {% endif %}
                    {% if user|can:'modify_targets' %}
                    <a class="dropdown-item text-danger" href="#" onclick="delete_organization({{ organization.id }})"><i class="fe-trash-2"></i>&nbsp;&nbsp;Delete Organization</a>
                    {% endif %}
                  </div>
                </div>
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>
{% endblock main_content %}

{% block page_level_script %}
<script src="{% static 'custom/custom.js' %}"></script>
<script src="{% static 'targetApp/js/custom_organization.js' %}"></script>
<script>
$(document).ready(function() {
  list_organization_table = $('#list_organization_table').DataTable({
    "oLanguage": {
      "oPaginate": { "sPrevious": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>', "sNext": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>' },
      "sInfo": "Showing page _PAGE_ of _PAGES_",
      "sSearch": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
      "sSearchPlaceholder": "Search...",
      "sLengthMenu": "Results :  _MENU_",
    },
    "dom": "<'dt--top-section'<'row'<'col-12 col-sm-6 d-flex justify-content-sm-start justify-content-center mt-sm-0 mt-3'f><'col-12 col-sm-6 d-flex justify-content-sm-end justify-content-center'l>>>" +
    "<'table-responsive'tr>" +
    "<'dt--bottom-section d-sm-flex justify-content-sm-between text-center'<'dt--pages-count  mb-sm-0 mb-3'i><'dt--pagination'p>>",
    "lengthMenu": [5, 10, 20, 30, 50, 100],
    "pageLength": 10,
    "initComplete": function(settings, json) {
      $('[data-toggle="tooltip"]').tooltip();
    }
  });
  multiCheck(list_organization_table);
});

function selectAllOrganizations(checkbox) {
  $('.organization-checkbox').prop('checked', checkbox.checked);
  toggleMultipleOrganizationButton();
}

function toggleMultipleOrganizationButton() {
  var checkedCount = $('.organization-checkbox:checked').length;
  if (checkedCount > 0) {
    $("#delete_multiple_button").removeClass("disabled");
  } else {
    $("#delete_multiple_button").addClass("disabled");
  }
  
  // Update the "select all" checkbox
  var totalCount = $('.organization-checkbox').length;
  $('#select_all_checkbox').prop('checked', checkedCount === totalCount);
}

function deleteMultipleOrganizations() {
  var checkedCount = $('.organization-checkbox:checked').length;
  if (!checkedCount) {
    swal({
      title: '',
      text: "Oops! No organizations have been selected!",
      type: 'error',
      padding: '2em'
    })
  } else {
    swal.queue([{
      title: 'Are you sure you want to delete ' + checkedCount + ' Organizations?',
      text: "This action is irreversible.",
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Delete',
      padding: '2em',
      showLoaderOnConfirm: true,
      preConfirm: function() {
        var selectedOrganizations = [];

        $('.organization-checkbox:checked').each(function() {
          selectedOrganizations.push($(this).val());
        });

        var data = {'type': 'organization', 'rows': selectedOrganizations}

        return fetch('/api/action/rows/delete/', {
          method: 'post',
          headers: {
            "X-CSRFToken": getCookie("csrftoken"),
            "Content-Type": "application/json"
          },
          body: JSON.stringify(data)
        }).then(res => res.json())
        .then(function (response) {
          if (response['status']) {
            // reload page
            location.reload();
          }
          else {
            Snackbar.show({
              text: 'Oops! Failed to delete organizations!',
              pos: 'top-right',
              duration: 1500,
              actionTextColor: '#fff',
              backgroundColor: '#e7515a',
            });
          }
        });
      }
    }])
  }
}
</script>
{% endblock page_level_script %}